from dvadmin.utils.serializers import CustomModelSerializer
from .models import SalesStrategy, SalesPerformance, MarketingPlan
from rest_framework import serializers
from datetime import datetime

class SalesStrategySerializer(CustomModelSerializer):
    """销售策略序列化器"""
    class Meta:
        model = SalesStrategy
        fields = "__all__"
        read_only_fields = ['status']

class SalesStrategyCreateUpdateSerializer(CustomModelSerializer):
    """销售策略创建/更新序列化器"""
    class Meta:
        model = SalesStrategy
        fields = '__all__'
        read_only_fields = ['status']

class SalesPerformanceSerializer(CustomModelSerializer):
    """销售业绩序列化器"""
    class Meta:
        model = SalesPerformance
        fields = "__all__"

class SalesPerformanceCreateUpdateSerializer(CustomModelSerializer):
    """销售业绩创建/更新序列化器"""
    class Meta:
        model = SalesPerformance
        fields = '__all__'
        
    def validate(self, attrs):
        """验证销售人员在同一月份是否已有业绩记录"""
        sales_person = attrs.get('sales_person')
        period = attrs.get('period')
        
        if not sales_person or not period:
            return attrs
            
        # 获取当前记录ID（更新时有效）
        instance_id = getattr(self.instance, 'id', None)
        
        # 将日期转换为当月第一天
        if isinstance(period, str):
            period_date = datetime.strptime(period, '%Y-%m-%d')
        else:
            period_date = period
            
        month_start = period_date.replace(day=1)
        
        # 检查同一销售人员同一月份是否已有记录
        existing_records = SalesPerformance.objects.filter(
            sales_person=sales_person,
            period__year=month_start.year,
            period__month=month_start.month
        )
        
        # 如果是更新操作，排除当前记录
        if instance_id:
            existing_records = existing_records.exclude(id=instance_id)
        
        if existing_records.exists():
            raise serializers.ValidationError({
                'period': f"销售人员 '{sales_person}' 在 {month_start.year}年{month_start.month}月 已有业绩记录"
            })
            
        return attrs

class MarketingPlanSerializer(CustomModelSerializer):
    """市场拓展计划序列化器"""
    class Meta:
        model = MarketingPlan
        fields = "__all__"

class MarketingPlanCreateUpdateSerializer(CustomModelSerializer):
    """市场拓展计划创建/更新序列化器"""
    class Meta:
        model = MarketingPlan
        fields = '__all__' 